package com.devplatform.service.impl.points;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.points.UserLevelMapper;
import com.devplatform.mapper.points.UserPointsMapper;
import com.devplatform.pojo.points.UserLevel;
import com.devplatform.pojo.points.UserPoints;
import com.devplatform.pojo.user.User;
import com.devplatform.service.impl.UserService;
import com.devplatform.service.points.PointsCommonService;
import com.devplatform.service.points.UserLevelService;
import com.devplatform.util.MessageUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 86156
 * @description 针对表【user_level】的数据库操作Service实现
 * @createDate 2025-09-28 10:59:57
 */
@Service
public class UserLevelServiceImpl extends ServiceImpl<UserLevelMapper, UserLevel>
        implements UserLevelService {

    @Resource
    UserService userService;
    @Resource
    private UserPointsMapper userPointsMapper;
    @Resource
    private UserLevelMapper userLevelMapper;
    @Resource
    private PointsCommonService pointsCommonService;
    @Resource
    private MessageUtil messageUtil;

    @Override
    public void calculateUserLevel(Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return;
        }

        // 确保主键有值
        if (user.getUserId() == null) {
            user.setUserId(userId);
        }

        Integer userCurrentLevel = user.getLevel();
        if (userCurrentLevel == null) {
            userCurrentLevel = 1;
        }

        UserPoints userPoints = userPointsMapper.selectByUserId(userId);
        int pointsTotal = userPoints == null ? 0 : userPoints.getTotalPoints();
        List<UserLevel> levelList = userLevelMapper.selectAllLevelsOrdered();
        UserLevel currentLevel = levelList.get(0);
        for (UserLevel level : levelList) {
            if (pointsTotal >= level.getMinPoints()) {
                currentLevel = level;
            } else {
                break;
            }
        }
        int currentLevelId = currentLevel.getLevelId();

        if (userCurrentLevel < currentLevelId) {
            user.setLevel(currentLevelId);
            boolean updated = userService.updateById(user);
            if (updated) {
                pointsCommonService.updatePointsDetail(userId, "LEVEL_UP", 50, false);
                String levelName = getLevelName(currentLevelId);
                messageUtil.sendLevelUpMessage(userId, userCurrentLevel, currentLevelId, levelName);
            } else {
                System.err.println("用户等级更新失败：userId=" + userId);
            }
        }
    }

    @Override
    public Map<String, Object> getUserLevel(Long userId) {
        UserPoints userPoints = userPointsMapper.selectByUserId(userId);
        int totalPoints = userPoints == null ? 0 : userPoints.getTotalPoints();
        //查看所有等级
        List<UserLevel> levelList = userLevelMapper.selectAllLevelsOrdered();
        // 匹配当前等级和下一级
        UserLevel currentLevel = levelList.get(0);
        for (UserLevel level : levelList) {
            if (totalPoints >= level.getMinPoints()) {
                currentLevel = level;
            }
        }
        UserLevel nextLevel = null;
        int currentIndex = levelList.indexOf(currentLevel);
        if (currentIndex < levelList.size() - 1) {
            nextLevel = levelList.get(currentIndex + 1);
        }

        // 计算升级进度
        float progress = 0;
        if (nextLevel != null && nextLevel.getMinPoints() > 0) {
            progress = (float) totalPoints / nextLevel.getMinPoints() * 100;
        } else {
            progress = 100; // 最高级进度100%
        }

        // 组装返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("currentLevel", currentLevel); // 当前等级
        result.put("nextLevel", nextLevel); // 下一级
        result.put("totalPoints", totalPoints); // 当前总积分
        result.put("needPoints", nextLevel != null ? nextLevel.getMinPoints() : 0); // 升级需达积分
        result.put("progress", String.format("%.1f", progress));
        return result;
    }

    @Override
    public UserLevel getUserLevelByLevel(Integer LevelId) {
        return userLevelMapper.selectById(LevelId);
    }

    @Override
    public String getLevelName(Integer LevelId) {
        return userLevelMapper.selectLevelNameById(LevelId);
    }


}



